package com.fan.binarysearch;

/**
 * 非递归的二分查找
 * @author 19252
 * @date 2020/8/2
 */
public class BinarySearchNonRecursive {

    public static void main(String[] args) {
        BinarySearchNonRecursive searchNonRecursive = new BinarySearchNonRecursive();
        int[] array = new int[]{-9,0,3,5,6,99,101};
        System.out.println(searchNonRecursive.search(array, 0));
    }

    /**
     * 在一个有序序列中查找目标值返回下标
     * @param array 有序的升序序列
     * @param target 目标值
     * @return 找到目标值在序列中的下标，未找到返回 -1
     */
    public int search(int[] array, int target){
        int right = array.length - 1;
        int mid;
        for (int i = 0; i <= right;) {
            mid = (i + right) / 2;
            if (array[mid] == target){
                return mid;
            }else if (array[mid] < target){
                i = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
